<script>
import MessageArea from '@/components/MessageArea'
import { getComment, postComment } from '@/api/blog'
import { debounce } from '@/utils/debounce'
export default {
  components: {
    MessageArea,
  },
  data() {
    return {
      data: null,
      isLoading: true,

      pager: 1,
      debounceMainScroll: null,

    }
  },
  computed: {
    list() {
      return this.data.rows
    },
    maxCommentsNum() {
      const maxNum = 50
      return this.data.rows.length >= maxNum
    }
  },
  methods: {
    async handSubmit(inputValue, callback) {
      const commentInfo = {
        nickname: inputValue.inputArea.trim(),
        content: inputValue.textArea.trim(),
        blogId: this.$route.params.id,
      }
      const resp = await postComment(commentInfo)
      this.data.rows.unshift(resp.data)
      this.data.total++
      callback('评论成功')
    },

    async getMoveComment() {
      if (this.maxCommentsNum) {
        return;
      }
      this.pager++
      this.isLoading = true
      const resp = await getComment(this.$route.params, this.pager)
      this.data.rows = this.data.rows.concat(resp.data.rows)
      this.isLoading = false
    },

    mainScroll(doms) {
      if (this.isLoading || !doms) {
        return;
      }
      const rang = 100 //距离误差
      const gap = doms.scrollHeight - doms.clientHeight - doms.scrollTop
      if (gap > rang) {
        return;
      }

      this.getMoveComment()
    }
  },
  created() {
    getComment(this.$route.params).then(resp => {
      this.data = resp.data
      this.isLoading = false
    })
  },
  mounted() {
    this.debounceMainScroll = debounce(this.mainScroll, 50)
    this.$bus.$on('mainScroll', this.debounceMainScroll)
  },
  beforeDestroy() {
    this.$bus.$off('mainScroll', this.debounceMainScroll)
  },
}
</script>



<template>
  <div class="blog-comment-contanier" v-loading="isLoading">
    <MessageArea v-if="data" title="评论列表" :subTitle="`(${data.total})`" :list="list" :isListLoading="isLoading"
      @submit="handSubmit" />
  </div>
</template>



<style lang='less' scoped>
.blog-comment-contanier {
  position: relative;
}
</style>